#include <algorithm>
#include <string>
#include <vector>
#include <utility>

#include "coefficient.h"
#include "helpers.h"
#include "parser.h"

using namespace std;

Coefficient Parser::GetResult() {
  vector<string> members = SplitByDelimiter(equation_, "=");
  return Coefficient::ReadCoefficientFromString(members[2]);
}

vector<pair<string, Coefficient> > Parser::GetLeftCoefficients() {
  vector<string> members = SplitByDelimiter(equation_, "=");
  vector<string> leftterms = SplitByDelimiter(members[0], "+");

  vector<pair<string, Coefficient> > result;
  for (int term = 0; term < (int)leftterms.size(); ++term) {
    if (term & 1) continue;
    vector<string> factors = SplitByDelimiter(leftterms[term], "*");
    if (factors.size() == 1) {
      result.push_back(make_pair(Strim(factors[0]),
                                 Coefficient::OneInstance()));
    }
    else {
      factors[0] = Strim(factors[0]);
      factors[2] = Strim(factors[2]);
      if (factors[0][0] != 'x') swap(factors[0], factors[2]);
      result.push_back(make_pair(
          Strim(factors[0]),
          Coefficient::ReadCoefficientFromString(factors[2]))
      );
    }
  }
  return result;
}
